package com.atguigu.orderservice.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.orderservice.entity.TOrder;
import com.atguigu.orderservice.entity.TPayLog;
import com.atguigu.orderservice.mapper.TPayLogMapper;
import com.atguigu.orderservice.service.TOrderService;
import com.atguigu.orderservice.service.TPayLogService;
import com.atguigu.orderservice.utils.HttpClient;
import com.atguigu.orderservice.utils.WePayPropertiesUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.wxpay.sdk.WXPayUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 支付日志表 服务实现类
 * </p>
 *
 * @author kaixuan
 * @since 2020-06-13
 */
@Service
public class TPayLogServiceImpl extends ServiceImpl<TPayLogMapper, TPayLog> implements TPayLogService {

    @Autowired
    private TOrderService orderService;

    /**
     * 根据订单号生成微信支付二维码
     * @param orderNo 订单号
     * @return
     */
    @Override
    public Map<String,Object> payCode(String orderNo) {
        try{
            //根据订单号获取订单信息
            QueryWrapper<TOrder> query = new QueryWrapper<>();
            query.eq("order_no",orderNo);
            TOrder order = orderService.getOne(query);
            Map<String,String> map = new HashMap<>();
            //设置请求微信生成支付二维码的参数
            map.put("appid", WePayPropertiesUtils.APP_ID);//appid
            map.put("mch_id", WePayPropertiesUtils.MCH_ID);//商户号
            map.put("nonce_str", WXPayUtil.generateNonceStr()); //随机字符串
            map.put("body", order.getCourseTitle());
            map.put("out_trade_no", orderNo); //订单号
            map.put("total_fee", order.getTotalFee().multiply(new BigDecimal("100")).longValue()+""); //金额
            map.put("spbill_create_ip", "127.0.0.1");//终端ip地址 本地测试 就是使用本地
            map.put("notify_url", "http://guli.shop/api/order/weixinPay/weixinNotify\n");//微信通知地址
            map.put("trade_type", "NATIVE");//微信支付交易类型
            HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/unifiedorder");//访问第三方接口并传递参数
            client.setXmlParam(WXPayUtil.generateSignedXml(map, WePayPropertiesUtils.PARTNER_KEY));//根据微信key设置参数
            client.setHttps(true);
            client.post();//发送post请求
            //返回微信第三方数据
            String xml = client.getContent();
            Map<String,String> result = WXPayUtil.xmlToMap(xml);//返回数据封装成map
            //返回数据
            Map<String,Object> m = new HashMap<>();
            m.put("out_trade_no", orderNo);
            m.put("course_id", order.getCourseId());
            m.put("total_fee", order.getTotalFee());
            m.put("result_code", result.get("result_code"));
            m.put("code_url", result.get("code_url"));
            //微信支付二维码2小时过期，可采取2小时未支付取消订单
            //redisTemplate.opsForValue().set(orderNo, map, 120, TimeUnit.MINUTES);
            return m;
        }catch (Exception e){
            e.printStackTrace();
            return new HashMap<>();
        }
    }

    /**
     * 根据订单号查询微信第三方支付状态
     * @param orderNo 订单号
     * @return
     */
    @Override
    public Map<String, String> queryPayStatus(String orderNo) {
        try{
            Map<String,String> map = new HashMap<>();
            map.put("appid", WePayPropertiesUtils.APP_ID);//appid
            map.put("mch_id", WePayPropertiesUtils.MCH_ID);//客户号
            map.put("out_trade_no", orderNo);
            map.put("nonce_str", WXPayUtil.generateNonceStr());//随机字符串
            HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/orderquery");
            client.setXmlParam(WXPayUtil.generateSignedXml(map,WePayPropertiesUtils.PARTNER_KEY));
            client.setHttps(true);
            client.post();
            //返回第三方数据
            String xml = client.getContent();
            Map<String,String> result = WXPayUtil.xmlToMap(xml);
            return result;
        }catch (Exception e){
            e.printStackTrace();
            return new HashMap<>();
        }
    }

    /**
     * 根据订单号更新订单状态
     * @param map
     */
    @Override
    @Transactional
    public void updateOrderStatus(Map<String,String> map) {
        QueryWrapper<TOrder> query = new QueryWrapper<>();
        query.eq("order_no",map.get("out_trade_no"));
        TOrder order = orderService.getOne(query);
        if (order.getStatus() == 1){
            return;
        }
        order.setStatus(1);
        orderService.updateById(order);

        //记录支付日志
        TPayLog payLog = new TPayLog();
        payLog.setOrderNo(order.getOrderNo());//支付订单号
        payLog.setPayTime(new Date());
        payLog.setPayType(1);//支付类型
        payLog.setTotalFee(order.getTotalFee());//总金额(分)
        payLog.setTradeState(map.get("trade_state"));//支付状态
        payLog.setTransactionId(map.get("transaction_id"));//微信订单号、流水号
        payLog.setAttr(JSONObject.toJSONString(map));
        baseMapper.insert(payLog);
    }
}
